<?php 
/**
 * sfWidgetFormPropelChoice represents a choice widget for a model.
 *
 * @package    symfony
 * @subpackage widget
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfWidgetFormPropelChoice.class.php 12803 2008-11-09 07:26:18Z fabien $
 */
class sfWidgetFormTree  extends sfWidgetForm
{
    /**
   * Configures the current widget.
   *
   * Available options:
   *
   *  * url:            The URL to call to get the choices to use (required)
   *  * config:         A JavaScript array that configures the JQuery autocompleter widget
   *  * value_callback: A callback that converts the value before it is displayed
   *
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetForm
   */
    protected function configure($options = array(), $attributes = array())
    {


        sfContext::getInstance()->getConfiguration()->loadHelpers('Url','I18N','Asset');
        //die(sfConfig::get('app_sf_jquery_web_dir').'/'.sfConfig::get('app_sf_jquery_core'));
        sfContext::getInstance()->getResponse()->addJavascript(sfConfig::get('sf_jquery_web_dir').'/'.sfConfig::get('sf_jquery_core'));
        sfContext::getInstance()->getResponse()->addJavascript(javascript_path('/sfCustomWidgetsPlugin/tree/jquery.tree.min.js',true));
        sfContext::getInstance()->getResponse()->addStylesheet('/sfCustomWidgetsPlugin/css/main.css');
        sfContext::getInstance()->getResponse()->addJavascript('/sfCustomWidgetsPlugin/js/main.js');

        $this->addOption('url' , sfContext::getInstance()->getController()->genUrl('@custom_widgets_bind_ajax_tree'));
        $this->addOption('pk' ,'id');
        //fks is array

        $this->addRequiredOption('fk_model_list');
        $this->addOption('use_hidden_field' , true);




        parent::configure($options, $attributes);


        //parent::configure($options, $attributes);
    }

    /**
   * @param  string $name        The element name
   * @param  string $value       The date displayed in this widget
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
    public function render($name, $value = null, $attributes = array(), $errors = array())
    {

        $id = $this->generateId( $name );

        $this->setOption('url',$this->getOption('url').'?html_id='.$id.'&value='.$value.'&fk_model_list='.urlencode(serialize($this->getOption('fk_model_list'))));

        $html = "";
        if($value){
            $fk_model_list = $this->getOption('fk_model_list');
            $fk_model_list_reversed =  array_reverse($fk_model_list);

            $f_values_reversed = array();
            $f_object_list_reversed = array();
            $this_value = $value;
            for( $i = 0 ; $i < count($fk_model_list_reversed) ; $i++ ) {
                //foreach ($fk_model_list_reversed as $fk_model){
                $this_model = sfInflector::camelize($fk_model_list_reversed[$i]);
                $next_model = !empty($fk_model_list_reversed[$i+1]) ? sfInflector::camelize($fk_model_list_reversed[$i+1]) : null;

                $obj = call_user_func_array(array($this_model.'Peer','retrieveByPK'),array($this_value));
                $f_values_reversed[] = $this_value;
                $f_object_list_reversed[] = $obj;

                //die($next_model);

                if($next_model){
                    //die('get'.$next_model);
                    $next_obj = call_user_func( array($obj,'get'.$next_model) );
                    //var_dump($next_obj);exit;
                    $this_value = $next_obj->getId();
                }
            }

            $f_object_list = array_reverse($f_object_list_reversed);


            $html .= implode(' > ', $f_object_list );

        }


        $hidden_field = $this->getOption('use_hidden_field') ? "<input type=hidden name='{$name}' value='{$value}' />" : '';
        

        $js = $this->getJavaScript($name , $value);

        $html = "<div class='tree-up-lable'>{$hidden_field}{$html}</div>\n".
        "<div id='tree_{$id}' class='tree tree-default'></div>\n{$js}";

        
        return "
        <div class='selectionArea'> 
                                <div class='label'> Sector / Industry </div>
                                    <div class='selection'>{$html}
                                     <div class='clear'></div>
                                    </div>
                                <div class='clear'></div>
                              </div>
        \n{$js}";


    }



    protected function getJavaScript($name , $value){
        $id = $this->generateId($name);
        $url = $this->getOption('url');

        $script1 = "";
        if($value) {
            $script1= <<<EOF
<script type="text/javascript">

</script>
EOF;

}
$script2= <<<EOF
<script type="text/javascript">
jQuery(function($){
    $('#tree_{$id}').tree({
        data : { 
		async : true,
		opts : {
			url : "{$url}"
	       	}//opts
    	}//data 
    	, callback :{
        	    beforedata : function(NODE, TREE_OBJ) { return { id : $(NODE).attr("struct") || 0 } }
        	  , onparse    : function(STR, TREE_OBJ) { 
        	       
        	       dummy = $('<ul></ul>').append(STR);
        	       parent_id = dummy.find('li:eq(0)').attr('parent');
        	       if( parent_id && typeof parent_id != 'undefined'){
            	       jq_parent = $( '#' +  parent_id );
        	           if(jq_parent.hasClass('checked')){
        	               dummy.find('li').addClass('checked');
        	           }//if has class
    	           }// if parent_id
    	           html = dummy.html();
    	           delete(dummy);
    	           return html;
        	   }//onparse
    	}//callback
    });
});





</script>
EOF;

return $script1.$script2;

}

}